package com.king.framework.security.service;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import com.king.common.enums.SsEnum;
import com.king.common.enums.UserStatus;
import com.king.common.exception.AssertHelper;
import com.king.common.utils.text.StringUtils;
import com.king.framework.base.domain.vo.LoginUser;
import com.king.modules.system.domain.SysOrgEntity;
import com.king.modules.system.domain.SysUserEntity;
import com.king.modules.system.service.SysOrgService;
import com.king.modules.system.service.SysUserService;

/**
 * 用户验证处理
 *
 * @author king
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {
	private static final Logger log = LoggerFactory.getLogger(UserDetailsServiceImpl.class);

	@Autowired
	private SysUserService userService;

	@Autowired
	private SysPasswordService passwordService;

	@Autowired
	private SysPermissionService permissionService;
	@Autowired
	private SysOrgService orgService;

	@Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
		SysUserEntity user = userService.selectUserByUserName(username);
		if (StringUtils.isNull(user)) {
			log.info("登录用户：{} 不存在.", username);
			AssertHelper.getInstance().throwException("登录用户：" + username + " 不存在");
		} else if (SsEnum.DELETED.getKey().equals(user.getSs())) {
			log.info("登录用户：{} 已被删除.", username);
			AssertHelper.getInstance().throwException("对不起，您的账号：" + username + " 已被删除");
		} else if (UserStatus.DISABLE.getCode().equals(user.getStatus())) {
			log.info("登录用户：{} 已被停用.", username);
			AssertHelper.getInstance().throwException("对不起，您的账号：" + username + " 已停用");
		}

		passwordService.validate(user);

		SysOrgEntity org = null;
		try {
			org = orgService.findByPK(user.getOrgid());
		} catch (Exception e) {
			e.printStackTrace();
		}
		return new LoginUser(user.getId(),user.getGroupid(), user.getOrgid(), org == null? "":org.getNodename(),
				user, permissionService.getMenuPermission(user));
	}

}
